package cn.zz.veggie.persistence.repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.collection.CollectionUtil;
import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.exception.classes.FatalErrorException;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.comm.util.NumberUtil;
import cn.zz.veggie.model.domain.Shop;
import cn.zz.veggie.model.query.ShopQuery;
import cn.zz.veggie.persistence.dao.ShopMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongq
 * @since 2024/7/26
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class ShopRepository {

	private final ShopMapper shopMapper;

	public Shop findById(Integer id) {
		if (NumberUtil.isPositive(id)) {
			return shopMapper.selectById(id);
		}
		return null;
	}

	public Map<Integer, Shop> findByIds(Collection<Integer> ids) {
		if (CollectionUtil.isEmpty(ids)) {
			return Collections.emptyMap();
		}
		final List<Shop> records = shopMapper.selectBatchIds(ids);
		return CollectorUtil.btmByKeyFun(records, Shop::getId);
	}

	public List<Shop> findByPage(ShopQuery query, PageQuery page) {
		final LambdaQueryWrapper<Shop> queryWrapper = query.toQueryWrapper();
		final Page<Shop> queryPage = query.toPage(page);
		List<Shop> result =  shopMapper.selectList(queryPage, queryWrapper);
		page.setTotal(((int) queryPage.getTotal()));
		return result;
	}

	public void save(Shop shop) {
		Objects.requireNonNull(shop);
		if (shop.getId() == null) {
			// insert
			final int effect = shopMapper.insert(shop);
			if (effect != 1) {
				throw new FatalErrorException("created shop fail ");
			}
			log.info("created shop for {}", shop.getId());
		} else {
			// update
			final int effect = shopMapper.updateById(shop);
			if (effect != 1) {
				throw new FatalErrorException("update shop fail ");
			}
			log.info("updated shop for {}", shop.getId());
		}
	}
}